import { useState, useMemo } from "react";
import { ToolCard } from "@/components/ToolCard";
import { SearchFilters } from "@/components/SearchFilters";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { 
  FileSpreadsheet, 
  Code, 
  Calculator, 
  BarChart3, 
  Table2,
  Code2,
  Palette,
  Globe,
  Layout,
  Zap,
  Sparkles,
  TrendingUp
} from "lucide-react";

// 模拟工具数据
const mockTools = [
  {
    id: "1",
    name: "Excel 数据分析大师",
    description: "强大的Excel数据分析工具，支持复杂的数据处理和可视化图表生成，让数据分析变得简单高效。",
    category: "excel" as const,
    rating: 4.8,
    downloads: 125000,
    views: 890000,
    lastUpdated: "2024年1月10日",
    author: "DataPro团队",
    tags: ["数据分析", "图表", "透视表", "自动化"],
    icon: <BarChart3 className="w-5 h-5" />,
    featured: true
  },
  {
    id: "2",
    name: "响应式HTML生成器",
    description: "快速生成现代化响应式HTML页面，内置多种模板和组件，支持一键导出和实时预览。",
    category: "html" as const,
    rating: 4.6,
    downloads: 98000,
    views: 560000,
    lastUpdated: "2024年1月8日",
    author: "WebBuilder",
    tags: ["响应式", "模板", "CSS", "前端"],
    icon: <Code2 className="w-5 h-5" />,
    featured: true
  },
  {
    id: "3",
    name: "Excel 公式助手",
    description: "智能的Excel公式生成和优化工具，支持复杂公式的可视化编辑和错误检测。",
    category: "excel" as const,
    rating: 4.5,
    downloads: 76000,
    views: 320000,
    lastUpdated: "2024年1月5日",
    author: "FormulaHub",
    tags: ["公式", "计算", "自动化", "优化"],
    icon: <Calculator className="w-5 h-5" />
  },
  {
    id: "4",
    name: "HTML美化工具",
    description: "一键美化和格式化HTML代码，支持代码压缩、语法高亮和错误检查功能。",
    category: "html" as const,
    rating: 4.3,
    downloads: 54000,
    views: 280000,
    lastUpdated: "2024年1月3日",
    author: "CodeClean",
    tags: ["格式化", "美化", "压缩", "语法"],
    icon: <Code className="w-5 h-5" />
  },
  {
    id: "5",
    name: "Excel 表格设计器",
    description: "专业的Excel表格样式设计工具，提供丰富的模板和自定义选项。",
    category: "excel" as const,
    rating: 4.7,
    downloads: 43000,
    views: 190000,
    lastUpdated: "2024年1月1日",
    author: "TableDesign",
    tags: ["设计", "样式", "模板", "美化"],
    icon: <Table2 className="w-5 h-5" />
  },
  {
    id: "6",
    name: "网页配色助手",
    description: "为HTML页面提供专业的配色方案建议，支持色彩搭配和无障碍设计。",
    category: "html" as const,
    rating: 4.4,
    downloads: 67000,
    views: 340000,
    lastUpdated: "2023年12月28日",
    author: "ColorMaster",
    tags: ["配色", "设计", "无障碍", "CSS"],
    icon: <Palette className="w-5 h-5" />
  }
];

export default function Marketplace() {
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedCategory, setSelectedCategory] = useState("all");
  const [selectedSort, setSelectedSort] = useState("popular");
  const [selectedTags, setSelectedTags] = useState<string[]>([]);

  // 提取所有标签
  const allTags = useMemo(() => {
    const tags = new Set<string>();
    mockTools.forEach(tool => {
      tool.tags.forEach(tag => tags.add(tag));
    });
    return Array.from(tags);
  }, []);

  // 筛选和排序工具
  const filteredTools = useMemo(() => {
    let filtered = mockTools.filter(tool => {
      // 搜索筛选
      if (searchQuery) {
        const searchLower = searchQuery.toLowerCase();
        if (!tool.name.toLowerCase().includes(searchLower) && 
            !tool.description.toLowerCase().includes(searchLower) &&
            !tool.tags.some(tag => tag.toLowerCase().includes(searchLower))) {
          return false;
        }
      }

      // 分类筛选
      if (selectedCategory !== "all" && tool.category !== selectedCategory) {
        return false;
      }

      // 标签筛选
      if (selectedTags.length > 0) {
        if (!selectedTags.some(tag => tool.tags.includes(tag))) {
          return false;
        }
      }

      return true;
    });

    // 排序
    switch (selectedSort) {
      case "newest":
        filtered = filtered.sort((a, b) => new Date(b.lastUpdated).getTime() - new Date(a.lastUpdated).getTime());
        break;
      case "rating":
        filtered = filtered.sort((a, b) => b.rating - a.rating);
        break;
      case "downloads":
        filtered = filtered.sort((a, b) => b.downloads - a.downloads);
        break;
      default: // popular
        filtered = filtered.sort((a, b) => b.views - a.views);
    }

    return filtered;
  }, [searchQuery, selectedCategory, selectedSort, selectedTags]);

  const handleTagToggle = (tag: string) => {
    setSelectedTags(prev => 
      prev.includes(tag) 
        ? prev.filter(t => t !== tag)
        : [...prev, tag]
    );
  };

  const featuredTools = filteredTools.filter(tool => tool.featured);
  const regularTools = filteredTools.filter(tool => !tool.featured);

  return (
    <div className="min-h-screen bg-background">
      {/* Hero 区域 */}
      <div className="relative overflow-hidden bg-gradient-primary">
        <div className="absolute inset-0 bg-black/20" />
        <div className="relative container mx-auto px-4 py-16">
          <div className="text-center text-white">
            <h1 className="text-4xl md:text-6xl font-bold mb-6">
              工具市场
              <Sparkles className="inline-block ml-3 w-8 h-8 animate-float" />
            </h1>
            <p className="text-xl md:text-2xl text-white/90 mb-8 max-w-2xl mx-auto">
              发现强大的 Excel 和 HTML 工具，提升您的工作效率
            </p>
            <div className="flex flex-wrap justify-center gap-4 text-sm">
              <Badge variant="secondary" className="bg-white/20 text-white border-white/30">
                <FileSpreadsheet className="w-4 h-4 mr-1" />
                Excel 工具
              </Badge>
              <Badge variant="secondary" className="bg-white/20 text-white border-white/30">
                <Globe className="w-4 h-4 mr-1" />
                HTML 工具
              </Badge>
              <Badge variant="secondary" className="bg-white/20 text-white border-white/30">
                <Zap className="w-4 h-4 mr-1" />
                高效率
              </Badge>
            </div>
          </div>
        </div>
      </div>

      <div className="container mx-auto px-4 py-8">
        <div className="grid lg:grid-cols-4 gap-8">
          {/* 侧边栏筛选 */}
          <div className="lg:col-span-1">
            <div className="sticky top-6">
              <h3 className="text-lg font-semibold mb-4">筛选工具</h3>
              <SearchFilters
                searchQuery={searchQuery}
                onSearchChange={setSearchQuery}
                selectedCategory={selectedCategory}
                onCategoryChange={setSelectedCategory}
                selectedSort={selectedSort}
                onSortChange={setSelectedSort}
                selectedTags={selectedTags}
                onTagToggle={handleTagToggle}
                allTags={allTags}
              />
            </div>
          </div>

          {/* 主内容区域 */}
          <div className="lg:col-span-3 space-y-8">
            {/* 统计信息 */}
            <div className="flex items-center justify-between">
              <div className="flex items-center space-x-4">
                <span className="text-muted-foreground">
                  找到 {filteredTools.length} 个工具
                </span>
                {selectedTags.length > 0 && (
                  <Button 
                    variant="ghost" 
                    size="sm"
                    onClick={() => setSelectedTags([])}
                  >
                    清除筛选
                  </Button>
                )}
              </div>
              <div className="flex items-center space-x-2 text-sm text-muted-foreground">
                <TrendingUp className="w-4 h-4" />
                <span>每日更新</span>
              </div>
            </div>

            {/* 精选工具 */}
            {featuredTools.length > 0 && (
              <div>
                <div className="flex items-center space-x-2 mb-6">
                  <Sparkles className="w-5 h-5 text-primary" />
                  <h2 className="text-2xl font-bold">精选工具</h2>
                </div>
                <div className="grid md:grid-cols-2 gap-6 mb-8">
                  {featuredTools.map((tool) => (
                    <ToolCard key={tool.id} {...tool} />
                  ))}
                </div>
              </div>
            )}

            {/* 所有工具 */}
            <div>
              <h2 className="text-2xl font-bold mb-6">
                {featuredTools.length > 0 ? "更多工具" : "所有工具"}
              </h2>
              {regularTools.length > 0 ? (
                <div className="grid md:grid-cols-2 xl:grid-cols-3 gap-6">
                  {regularTools.map((tool) => (
                    <ToolCard key={tool.id} {...tool} />
                  ))}
                </div>
              ) : (
                <div className="text-center py-12">
                  <Layout className="w-16 h-16 mx-auto text-muted-foreground mb-4" />
                  <h3 className="text-lg font-semibold mb-2">暂无相关工具</h3>
                  <p className="text-muted-foreground">
                    试试调整筛选条件或搜索其他关键词
                  </p>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}